<template>
  <div class="order-page">
    <h1 class="page-title">订单信息</h1>

    <!-- 订单列表 -->
    <el-table :data="orders" border style="width: 100%">
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="订单总价" align="center">
        <template #default="{ row }">
          ¥ {{ row.totalPrice.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center">
        <template #default="{ row }">
          <el-tag :type="getOrderStatusTagType(row.orderStatus)">
            {{ getOrderStatusText(row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center">
        <template #default="{ row }">
          <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
            {{ getPaymentStatusText(row.paymentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" />
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button
              type="primary"
              size="small"
              @click="viewOrderDetails(row.orderId)"
          >
            详情
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="deleteOrder(row.orderId)"
              :disabled="row.orderStatus !== 1"
          >
            删除
          </el-button>
          <el-button
              type="success"
              size="small"
              @click="confirmReceipt(row.orderId)"
              :disabled="row.orderStatus !== 2"
          >
            确认收货
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="fetchOrders"
        @size-change="handlePageSizeChange"
    />

    <!-- 弹窗：展示订单详情 -->
    <el-dialog v-model="orderItemDialogVisible" title="订单详情" width="50%">
      <el-table :data="orderItemList" border>
        <el-table-column label="菜品名称" prop="dishName" align="center" />
        <el-table-column label="菜品描述" prop="dishDescription" align="center" />
        <el-table-column label="图片" align="center">
          <template #default="{ row }">
            <el-image
                style="width: 100px; height: 100px"
                :preview-src-list="[row.dishImageUrl]"
                :src="row.dishImageUrl"
                fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="price" align="center" />
        <el-table-column label="数量" prop="quantity" align="center" />
        <el-table-column label="总价" prop="totalPrice" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { apiGet, apiPost } from '@/utils/api';
import type { Order, OrderItem } from '@/types/entity';
import { useUserStore } from '@/store/modules/user';

const userStore = useUserStore();

// 定义响应式的订单列表
const orders = ref<Order[]>([]);

// 分页参数
const pageNo = ref(1); // 当前页码
const pageSize = ref(5); // 每页显示条数
const total = ref(0); // 总条数

// 订单详情弹窗的显示与隐藏
const orderItemDialogVisible = ref(false);

// 订单详情列表
const orderItemList = ref<OrderItem[]>([]);

// 从后端获取订单数据
const fetchOrders = async () => {
  const { data } = await apiGet('/order/findAll', {
    page: pageNo.value,
    limit: pageSize.value,
    userId: userStore.id,
  });
  orders.value = data.data; // 假设返回的数据结构为 { data: Order[], total: number }
  total.value = data.count; // 更新总条数
};

// 查看订单详情
const viewOrderDetails = async (orderId: number) => {
  const { data } = await apiGet('/orderItem/getAllByOrderId', { orderId });
  orderItemList.value = data; // 假设返回的数据结构为 OrderItem[]
  orderItemDialogVisible.value = true; // 显示弹窗
};

// 删除订单
const deleteOrder = async (orderId: number) => {
  await ElMessageBox.confirm('确定删除该订单吗？', '提示', {
    type: 'warning',
  });
  await apiPost('/order/delete', { orderId });
  await fetchOrders(); // 刷新订单列表
};

// 确认收货
const confirmReceipt = async (orderId: number) => {
  await ElMessageBox.confirm('确认收到货了吗？', '提示', {
    type: 'warning',
  });
  await apiPost('/order/edit', { orderId, orderStatus: 3 });
  await fetchOrders(); // 刷新订单列表
};

// 处理分页大小变化
const handlePageSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  pageNo.value = 1; // 重置页码
  fetchOrders(); // 重新加载数据
};

// 获取订单状态标签类型
const getOrderStatusTagType = (status: number) => {
  switch (status) {
    case 1:
      return 'info'; // 待处理
    case 2:
      return 'warning'; // 已发货
    case 3:
      return 'success'; // 已完成
    default:
      return 'danger'; // 未知状态
  }
};

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '待处理';
    case 2:
      return '已发货';
    case 3:
      return '已完成';
    default:
      return '未知状态';
  }
};

// 获取支付状态标签类型
const getPaymentStatusTagType = (status: number) => {
  switch (status) {
    case 1:
      return 'info'; // 支付中
    case 2:
      return 'success'; // 支付成功
    case 3:
      return 'danger'; // 支付失败
    case 4:
      return 'warning'; // 已退款
    case 5:
      return 'warning'; // 部分退款
    case 6:
      return 'danger'; // 支付取消
    case 7:
      return 'danger'; // 支付超时
    case 8:
      return 'danger'; // 支付关闭
    case 9:
      return 'danger'; // 支付异常
    case 10:
      return 'warning'; // 待支付
    default:
      return 'danger'; // 未知状态
  }
};

// 获取支付状态文本
const getPaymentStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '支付中';
    case 2:
      return '支付成功';
    case 3:
      return '支付失败';
    case 4:
      return '已退款';
    case 5:
      return '部分退款';
    case 6:
      return '支付取消';
    case 7:
      return '支付超时';
    case 8:
      return '支付关闭';
    case 9:
      return '支付异常';
    case 10:
      return '待支付';
    default:
      return '未知状态';
  }
};

// 在组件挂载时获取订单数据
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>